<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>每日一面--MyBatis | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="每天一篇面试小知识  本篇着重介绍一下 MyBatis   写在前面 用久了 MyBatis 的逆向工程，原生的写法有点生疏了，趁着想起来赶紧复习一下！">
<meta property="og:type" content="article">
<meta property="og:title" content="每日一面--MyBatis">
<meta property="og:url" content="https://curry3035.gitee.io/posts/56080/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="每天一篇面试小知识  本篇着重介绍一下 MyBatis   写在前面 用久了 MyBatis 的逆向工程，原生的写法有点生疏了，趁着想起来赶紧复习一下！">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-07-23T00:58:58.000Z">
<meta property="article:modified_time" content="2022-05-26T18:17:17.003Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="进阶">
<meta property="article:tag" content="MyBatis">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/56080/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '每日一面--MyBatis',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-27 02:17:17'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">每日一面--MyBatis</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-07-23T00:58:58.000Z" title="发表于 2021-07-23 08:58:58">2021-07-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-26T18:17:17.003Z" title="更新于 2022-05-27 02:17:17">2022-05-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%9D%A2%E8%AF%95%E7%AF%87/">面试篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="每日一面--MyBatis"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>每天一篇面试小知识</p>
</blockquote>
<p><strong>本篇着重介绍一下 MyBatis</strong></p>
<hr>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/mybatis-logo.png"></p>
<p><strong>写在前面</strong></p>
<p>用久了 MyBatis 的逆向工程，原生的写法有点生疏了，趁着想起来赶紧复习一下！</p>
<span id="more"></span>



<h2 id="关于-MyBatis"><a href="#关于-MyBatis" class="headerlink" title="关于 MyBatis"></a>关于 MyBatis</h2><h3 id="什么是-MyBatis？"><a href="#什么是-MyBatis？" class="headerlink" title="什么是 MyBatis？"></a>什么是 MyBatis？</h3><p>Mybatis是一个半自动化的持久层框架，一般我们都分为三层，控制层，业务层，持久层，所谓的持久层就是专门负责写入数据库的层次。</p>
<h3 id="MyBatis-为什么说他是半自动化？"><a href="#MyBatis-为什么说他是半自动化？" class="headerlink" title="MyBatis 为什么说他是半自动化？"></a>MyBatis 为什么说他是半自动化？</h3><p>Hibernate 和 JPA 我们可以称为全自动化，所谓的全自动化就是他给我们直接省去了大量的 jdbc 代码，就连sql 语句我们都不用写，所以我们称他为全自动化，而Mybatis之所以称为半自动化就是虽然帮我省去了 jdbc 的一些重复代码，但是 sql 语句仍然需要我们自己写。</p>
<h3 id="MyBatis-的优点是什么？"><a href="#MyBatis-的优点是什么？" class="headerlink" title="MyBatis 的优点是什么？"></a>MyBatis 的优点是什么？</h3><p>MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架；</p>
<p><strong>MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集；</strong></p>
<p>MyBatis可以使用简单的XML或注解用于配置和原始映射，将接口和 Java 的 POJO（Plain Old Java Objects，普通的Java对象）映射成数据库中的记录；</p>
<p><strong>并且mybatis还给我们提供了很多第三方插件（分页插件 / 逆向工程）；</strong></p>
<h3 id="MyBatis有哪些缺点？"><a href="#MyBatis有哪些缺点？" class="headerlink" title="MyBatis有哪些缺点？"></a>MyBatis有哪些缺点？</h3><ol>
<li>编写 SQL 语句时工作量很大，尤其是字段多、关联表多时，更是如此。</li>
<li>SQL 语句依赖于数据库，导致数据库移植性差，不能更换数据库。</li>
<li>框架还是比较简陋，功能尚有缺失，虽然简化了数据绑定代码，但是整个底层数据库查询实际还是要自己写的，工作量也比较大，而且不太容易适应快速数据库修改。</li>
<li>二级缓存机制不佳。</li>
</ol>
<h3 id="如何选择？"><a href="#如何选择？" class="headerlink" title="如何选择？"></a>如何选择？</h3><p>面对这些持久化框架我们应该如何来进行选择呢？</p>
<p>选型上都会拿 MyBatis 和 JPA 两个持久层框架一起使用，JPA 用来简单查询和新增修改是非常方便的，并且支持一对多关系。然后复杂的查询语句用 MyBatis 来完成。、</p>
<br/>

<h2 id="MyBatis-常用标签和注解"><a href="#MyBatis-常用标签和注解" class="headerlink" title="MyBatis 常用标签和注解"></a>MyBatis 常用标签和注解</h2><h3 id="了解一下"><a href="#了解一下" class="headerlink" title="了解一下"></a>了解一下</h3><p>MyBatis的常用标签有很多，比如</p>
<p><code>&lt;sql id=&quot;&quot;&gt;</code>：预定义可以复用的sql语句</p>
<p><code>&lt;include refid=&quot;&quot;&gt;</code>：根据id引用定义的sql语句</p>
<p><code>&lt;trim&gt;</code>：空白补全，配合<code>&lt;if&gt;</code>标签使用</p>
<p><code>&lt;if test=&quot;&quot;&gt;</code>：条件判断，该语句返回的true，则该标签内的语句就生效</p>
<p><code>&lt;bind name=&quot;&quot; value=&quot;&quot;&gt;</code>：创建一个变量，并且可以绑定到上下文</p>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;BaseResultMap&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.entity.User&quot;</span> &gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">jdbcType</span>=<span class="string">&quot;INTEGER&quot;</span> /&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;name&quot;</span> <span class="attr">property</span>=<span class="string">&quot;name&quot;</span> <span class="attr">jdbcType</span>=<span class="string">&quot;VARCHAR&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="顶级标签"><a href="#顶级标签" class="headerlink" title="顶级标签"></a>顶级标签</h3><h4 id="1、sql"><a href="#1、sql" class="headerlink" title="1、sql"></a>1、sql</h4><p><strong>作用：【可被其他语句引用的可重用语句块】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">&quot;valid&quot;</span>&gt;</span> where id = 1 <span class="tag">&lt;/<span class="name">sql</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">&lt;!-- 引用 sql --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span> = <span class="string">&#x27;queryUser&#x27;</span> <span class="attr">resultMap</span>=<span class="string">&quot;BaseResultMap&quot;</span>&gt;</span></span><br><span class="line">    select * from user </span><br><span class="line">    <span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span> = <span class="string">&#x27;valid&#x27;</span>&gt;</span><span class="tag">&lt;/<span class="name">include</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="2、insert"><a href="#2、insert" class="headerlink" title="2、insert"></a>2、insert</h4><p><strong>作用：【映射插入语句】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insert&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.entity.User&quot;</span> &gt;</span></span><br><span class="line">    insert into user (id, name)</span><br><span class="line">    values (#&#123;id,jdbcType=INTEGER&#125;, #&#123;name,jdbcType=VARCHAR&#125;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="3、update"><a href="#3、update" class="headerlink" title="3、update"></a>3、update</h4><p><strong>作用：【映射更新语句】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateUser&quot;</span>&gt;</span></span><br><span class="line">  update User set</span><br><span class="line">    name = #&#123;name&#125;,</span><br><span class="line">    sex= #&#123;sex&#125;</span><br><span class="line">  where id = #&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="4、delete"><a href="#4、delete" class="headerlink" title="4、delete"></a>4、delete</h4><p><strong>作用：【映射删除语句】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">&quot;deleteUser&quot;</span>&gt;</span></span><br><span class="line">  delete from User where id = #&#123;id&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="动态sql标签"><a href="#动态sql标签" class="headerlink" title="动态sql标签"></a>动态sql标签</h3><p><font color=#008000><strong>常用标签：&lt; if &gt;、&lt; where &gt;、&lt; trim &gt;、&lt; foreach &gt;</strong></font></p>
<h4 id="1、if"><a href="#1、if" class="headerlink" title="1、if"></a>1、if</h4><p><strong>作用：【where 语句的条件动态拼接】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findUserByName&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">  SELECT * FROM User</span><br><span class="line">  WHERE valid = 1</span><br><span class="line">  <span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;name!= null&quot;</span>&gt;</span></span><br><span class="line">    AND name like #&#123;name&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h4 id="2、choose-when-otherwise"><a href="#2、choose-when-otherwise" class="headerlink" title="2、choose (when, otherwise)"></a>2、choose (when, otherwise)</h4><p><strong>作用：【多条件分支，相当于Java中的switch语句】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findUser&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">  SELECT * FROM User WHERE age = 26</span><br><span class="line">  <span class="tag">&lt;<span class="name">choose</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;name!= null&quot;</span>&gt;</span></span><br><span class="line">      AND name like #&#123;name&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">when</span> <span class="attr">test</span>=<span class="string">&quot;sex!= null &quot;</span>&gt;</span></span><br><span class="line">      AND sex like #&#123;sex&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">when</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">otherwise</span>&gt;</span></span><br><span class="line">      AND valid = 1</span><br><span class="line">    <span class="tag">&lt;/<span class="name">otherwise</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">choose</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>choose 有点像 Java 中的 switch 语句。choose执行过程中按顺序判断 when 中的条件出否成立，如果有一个成立，则 choose 结束。当 choose 中所有 when 的条件都不满则时，则执行 otherwise 中的 sql。</p>
<h4 id="3、trim-where-set"><a href="#3、trim-where-set" class="headerlink" title="3、trim (where, set)"></a>3、trim (where, set)</h4><p><strong>作用：【用于添加 SQL 语句的前缀或者后缀】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">trim</span> <span class="attr">prefix</span>=<span class="string">&quot;WHERE&quot;</span> <span class="attr">prefixOverrides</span>=<span class="string">&quot;AND | OR &quot;</span>&gt;</span></span><br><span class="line">  ...</span><br><span class="line"><span class="tag">&lt;/<span class="name">trim</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">&lt;!-- set 元素会动态前置 SET 关键字，同时也会删掉无关的逗号 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">trim</span> <span class="attr">prefix</span>=<span class="string">&quot;SET&quot;</span> <span class="attr">suffixOverrides</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">  ...</span><br><span class="line"><span class="tag">&lt;/<span class="name">trim</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>所以可利用 &lt; trim &gt; 来代替 &lt; where &gt; 的功能</p>
<ul>
<li><p>prefix：指定sql语句拼接的前缀</p>
</li>
<li><p>subfix：指定sql语句拼接的后缀</p>
</li>
<li><p> prefixOverrides：指定sql语句前面要去除的关键字或字符，如AND 逗号 括号等</p>
</li>
<li><p> suffixOverrides：指定sql语句后面要去除的关键字或字符</p>
</li>
</ul>
<h4 id="4、foreach"><a href="#4、foreach" class="headerlink" title="4、foreach"></a>4、foreach</h4><p><strong>作用：【用于在 SQL 语句中迭代一个集合，可用在构建 in 条件中】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUser&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">  SELECT *</span><br><span class="line">  FROM User</span><br><span class="line">  WHERE ID in</span><br><span class="line">  <span class="tag">&lt;<span class="name">foreach</span> <span class="attr">item</span>=<span class="string">&quot;item&quot;</span> <span class="attr">index</span>=<span class="string">&quot;index&quot;</span> <span class="attr">collection</span>=<span class="string">&quot;list&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span>&gt;</span></span><br><span class="line">        #&#123;item&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>collection=”要遍历的集合” </li>
<li>item = “可以在元素体内使用的集合项”</li>
<li>index = “索引”</li>
<li>open = “开始字符串”</li>
<li>separator = “分隔符”</li>
<li>close = “结束字符串”</li>
</ul>
<h4 id="5、bind"><a href="#5、bind" class="headerlink" title="5、bind"></a>5、bind</h4><p><strong>作用：【标签表示在表达式以外创建一个变量，并将其绑定到当前的上下文】</strong></p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUser&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;user&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">bind</span> <span class="attr">name</span>=<span class="string">&quot;pattern&quot;</span> <span class="attr">value</span>=<span class="string">&quot;&#x27;%&#x27; + _parameter.getTitle() + &#x27;%&#x27;&quot;</span> /&gt;</span></span><br><span class="line">  SELECT * FROM User</span><br><span class="line">  WHERE name LIKE #&#123;pattern&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<h2 id="MyBatis-使用"><a href="#MyBatis-使用" class="headerlink" title="MyBatis 使用"></a>MyBatis 使用</h2><h3 id="1、MyBatis-中的-resultType-和-resultMap"><a href="#1、MyBatis-中的-resultType-和-resultMap" class="headerlink" title="1、MyBatis 中的 resultType 和 resultMap"></a>1、MyBatis 中的 resultType 和 resultMap</h3><p>resultType 用于返回值只有一个字段的类型，resultMap 用于返回值有多个字段的类型。至于结果是 List 还是一个，则在 Mapper 中定义返回值是List还是单个。</p>
<p>使用 resultType：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;count&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;java.lang.Integer&quot;</span>&gt;</span>  </span><br><span class="line">        SELECT count(*) FROM USER  </span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span>  </span><br></pre></td></tr></table></figure>

<p>使用 resultMap：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">&quot;com.entity.Blog&quot;</span> <span class="attr">id</span>=<span class="string">&quot;BlogResult&quot;</span>&gt;</span>    </span><br><span class="line">   <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span>/&gt;</span>    </span><br><span class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;title&quot;</span> <span class="attr">property</span>=<span class="string">&quot;title&quot;</span>/&gt;</span>    </span><br><span class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;content&quot;</span> <span class="attr">property</span>=<span class="string">&quot;content&quot;</span>/&gt;</span>    </span><br><span class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">&quot;owner&quot;</span> <span class="attr">property</span>=<span class="string">&quot;owner&quot;</span>/&gt;</span>    </span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span>   </span><br><span class="line">    </span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectBlog&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;int&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;BlogResult&quot;</span>&gt;</span>    </span><br><span class="line">   select * from t_blog where id = #&#123;id&#125;    </span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span>  </span><br></pre></td></tr></table></figure>

<h3 id="2、xml中的timestamp比较"><a href="#2、xml中的timestamp比较" class="headerlink" title="2、xml中的timestamp比较"></a>2、xml中的timestamp比较</h3><p><strong>转义字符表</strong></p>
<table>
<thead>
<tr>
<th>转义</th>
<th>符号</th>
</tr>
</thead>
<tbody><tr>
<td><code>&amp;lt;</code></td>
<td>&lt;</td>
</tr>
<tr>
<td><code>&amp;gt;</code></td>
<td>&gt;</td>
</tr>
<tr>
<td><code>&amp;amp;</code></td>
<td>&amp;</td>
</tr>
<tr>
<td><code>&amp;apos;</code></td>
<td>’</td>
</tr>
<tr>
<td><code>&amp;quot;</code></td>
<td>“</td>
</tr>
</tbody></table>
<h3 id="3、MyBatis-批量插入"><a href="#3、MyBatis-批量插入" class="headerlink" title="3、MyBatis 批量插入"></a>3、MyBatis 批量插入</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span> ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">mapper</span> <span class="keyword">PUBLIC</span> <span class="string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span> <span class="string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span> &gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.mapper.UserMapper&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insertForeach&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;java.util.List&quot;</span> <span class="attr">useGeneratedKeys</span>=<span class="string">&quot;false&quot;</span>&gt;</span></span><br><span class="line">	insert into user</span><br><span class="line">	( id,name )</span><br><span class="line">	values</span><br><span class="line">	<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;list&quot;</span> <span class="attr">item</span>=<span class="string">&quot;item&quot;</span> <span class="attr">index</span>=<span class="string">&quot;index&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">	  (</span><br><span class="line">	    #&#123;item.id&#125;,</span><br><span class="line">	    #&#123;item.name&#125;</span><br><span class="line">	  )</span><br><span class="line">    <span class="tag">&lt;/<span class="name">foreach</span>&gt;</span>		</span><br><span class="line">  <span class="tag">&lt;/<span class="name">insert</span>&gt;</span>    </span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="4、MyBatis-传递多个参数"><a href="#4、MyBatis-传递多个参数" class="headerlink" title="4、MyBatis 传递多个参数"></a>4、MyBatis 传递多个参数</h3><h4 id="方法一-使用map接口传递参数"><a href="#方法一-使用map接口传递参数" class="headerlink" title="方法一:使用map接口传递参数"></a>方法一:使用map接口传递参数</h4><p>map是一个键值对应的集合，使用者要通过阅读它的键，才能明了其作用；其次，使用map不能限定其传递的数据类型，因此业务性质不强，可读性差。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;Role&gt; <span class="title function_">findRolesByMap</span><span class="params">(Map&lt;String, Object&gt; parameterMap)</span>;</span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findRolesByMap&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;map&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;role&quot;</span>&gt;</span></span><br><span class="line">    select id, role_name as roleName, note from t_role where role_name like concat(&#x27;%&#x27;, #&#123;roleName&#125;, &#x27;%&#x27;) and note like concat(&#x27;%&#x27;, #&#123;note&#125;, &#x27;%&#x27;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="方法二-使用注解传递多个参数"><a href="#方法二-使用注解传递多个参数" class="headerlink" title="方法二:使用注解传递多个参数"></a>方法二:使用注解传递多个参数</h4><p>注解 @Param 可以通过它去定义映射器的参数名称</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;Role&gt; <span class="title function_">findRolesByAnnotation</span><span class="params">(<span class="meta">@Param(&quot;roleName&quot;)</span> String rolename, <span class="meta">@Param(&quot;note&quot;)</span> String note)</span>;</span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findRolesByAnnotation&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;role&quot;</span>&gt;</span></span><br><span class="line">    select id, role_name as roleName, note from t_role where role_name like concat(&#x27;%&#x27;, #&#123;roleName&#125;, &#x27;%&#x27;) and note like concat(&#x27;%&#x27;, #&#123;note&#125;, &#x27;%&#x27;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="方法三-通过Java-Bean传递多个参数"><a href="#方法三-通过Java-Bean传递多个参数" class="headerlink" title="方法三:通过Java Bean传递多个参数"></a>方法三:通过Java Bean传递多个参数</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;Role&gt; <span class="title function_">findRolesByBean</span><span class="params">(RoleParams roleParam)</span>;</span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findRolesByBean&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.entity.RoleParams&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;role&quot;</span>&gt;</span></span><br><span class="line">    select id, role_name as roleName, note from t_role where role_name like concat(&#x27;%&#x27;, #&#123;roleName&#125;, &#x27;%&#x27;) and note like concat(&#x27;%&#x27;, #&#123;note&#125;, &#x27;%&#x27;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="方法四-混合使用"><a href="#方法四-混合使用" class="headerlink" title="方法四:混合使用"></a>方法四:混合使用</h4><p>不指定 parameterType ，需要指定具体的属性。</p>
 <figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> List&lt;Role&gt; <span class="title function_">findByMix</span><span class="params">(<span class="meta">@Param(&quot;params&quot;)</span> RoleParams roleParams, <span class="meta">@Param(&quot;page&quot;)</span> PageParam PageParam)</span>;</span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;findByMix&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;role&quot;</span>&gt;</span></span><br><span class="line">    select id, role_name as roleName, note from t_role</span><br><span class="line">    where role_name like concat(&#x27;%&#x27;, #&#123;params.roleName&#125;, &#x27;%&#x27;) and note like concat(&#x27;%&#x27;, #&#123;params.note&#125;, &#x27;%&#x27;) limit #&#123;page.start&#125;, #&#123;page.limit&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>当 n≤5 时，使用 @Param 注解传递多个参数；</li>
<li>当 n＞5 时，建议使用 Java Bean 方式；</li>
</ul>
<h3 id="5、数据库字段名和实体类属性名不一致的问题（驼峰匹配）"><a href="#5、数据库字段名和实体类属性名不一致的问题（驼峰匹配）" class="headerlink" title="5、数据库字段名和实体类属性名不一致的问题（驼峰匹配）"></a>5、数据库字段名和实体类属性名不一致的问题（驼峰匹配）</h3><h4 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h4><p>查询数据的时候，查不到 userName 的信息，原因：数据库的字段名是 user_name POJO中的属性名字是userName<br>两端不一致，造成mybatis无法填充对应的字段信息。修改方法：在sql语句中使用别名。</p>
<h4 id="解决方案一"><a href="#解决方案一" class="headerlink" title="解决方案一"></a>解决方案一</h4><p>开启驼峰匹配：相当于去掉数据库名字中的下划线，然后在与java中的属性名进行对应。</p>
<p>数据库中的 user_name 和 java 属性中的 userName 是一样的。</p>
<figure class="highlight properties"><table><tr><td class="code"><pre><span class="line"><span class="attr">mybatis.configuration.map-underscore-to-camel-case</span>=<span class="string">true</span></span><br></pre></td></tr></table></figure>

<h4 id="解决方案二"><a href="#解决方案二" class="headerlink" title="解决方案二"></a>解决方案二</h4><p>resultType 类指定返回值的类型，这样 Mybatis 会帮我们自动映射属性，即只有当类的属性名和字段名相同时，才存在映射关系。</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUserList&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.entity.User&quot;</span>&gt;</span></span><br><span class="line">    select * from user;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>如果我们属性名和字段名不同那么我们就需要用 resultMap 来重新映射。</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">&quot;UserMapper&quot;</span> <span class="attr">type</span>=<span class="string">&quot;com.ariverh.pojo.User&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;id&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;userName&quot;</span> <span class="attr">column</span>=<span class="string">&quot;name&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUserList&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;UserMapper&quot;</span>&gt;</span></span><br><span class="line">    select id,name as userName from user;</span><br><span class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>



<h2 id="MyBatis缓存机制"><a href="#MyBatis缓存机制" class="headerlink" title="MyBatis缓存机制"></a>MyBatis缓存机制</h2><h3 id="了解一下-1"><a href="#了解一下-1" class="headerlink" title="了解一下"></a>了解一下</h3><p>缓存机制减轻数据库压力，提高数据库性能</p>
<p>mybatis 的缓存分为两级：一级缓存、二级缓存</p>
<p>namespace 指定的是对应的 mapper 接口</p>
<h3 id="一级缓存："><a href="#一级缓存：" class="headerlink" title="一级缓存："></a>一级缓存：</h3><p>一级缓存为 <code>sqlsesson</code> 缓存，缓存的数据只在 SqlSession 内有效。在操作数据库的时候需要先创建 SqlSession 会话对象，在对象中有一个 HashMap 用于存储缓存数据，此 HashMap 是当前会话对象私有的，别的 SqlSession 会话对象无法访问。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/mybatis-sql-session-01.jpg" style="zoom: 50%;" />

<h4 id="具体流程"><a href="#具体流程" class="headerlink" title="具体流程"></a>具体流程</h4><p>第一次执行 select 完毕会将查到的数据写入 SqlSession 内的 HashMap 中缓存起来</p>
<p>第二次执行 select 会从缓存中查数据，如果 select 同传参数一样，那么就能从缓存中返回数据，不用去数据库了，从而提高了效率。</p>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>1、如果 SqlSession 执行了 DML 操作（insert、update、delete），并 commit 了，那么 mybatis 就会清空当前 SqlSession 缓存中的所有缓存数据，这样可以保证缓存中的存的数据永远和数据库中一致，避免出现差异</p>
<p>2、当一个 SqlSession 结束后那么他里面的一级缓存也就不存在了， mybatis 默认是开启一级缓存，不需要配置</p>
<p>3、 mybatis 的缓存是基于 [namespace:sql语句:参数] 来进行缓存的，意思就是， SqlSession 的 HashMap 存储缓存数据时，是使用 [namespace:sql:参数] 作为 key ，查询返回的语句作为 value 保存的</p>
<p><strong>4、一级缓存只在数据库会话内部共享。</strong></p>
<h3 id="二级缓存："><a href="#二级缓存：" class="headerlink" title="二级缓存："></a>二级缓存：</h3><h4 id="前言-1"><a href="#前言-1" class="headerlink" title="前言"></a>前言</h4><p>在上文中提到的一级缓存中，其最大的共享范围就是一个 SqlSession 内部，如果多个 SqlSession 之间需要共享缓存，则需要使用到二级缓存。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/mybatis-sql-session-02.png" style="zoom: 80%;" />



<h4 id="具体流程-1"><a href="#具体流程-1" class="headerlink" title="具体流程"></a>具体流程</h4><p>二级缓存开启后，同一个namespace下的所有操作语句，都影响着同一个Cache，即二级缓存被多个SqlSession共享，是一个全局的变量。</p>
<p>当开启缓存后，数据的查询执行的流程就是 二级缓存 -&gt; 一级缓存 -&gt; 数据库。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ol>
<li>MyBatis的二级缓存相对于一级缓存来说，实现了<code>SqlSession</code>之间缓存数据的共享，同时粒度更加的细，能够到<code>namespace</code>级别，通过Cache接口实现类不同的组合，对Cache的可控性也更强。</li>
<li>MyBatis在多表查询时，极大可能会出现脏数据，有设计上的缺陷，安全使用二级缓存的条件比较苛刻。</li>
<li>在分布式环境下，由于默认的MyBatis Cache实现都是基于本地的，分布式环境下必然会出现读取到脏数据，需要使用集中式缓存将MyBatis的Cache接口实现，有一定的开发成本，直接使用Redis、Memcached等分布式缓存可能成本更低，安全性也更高。</li>
</ol>
<br/>

<h2 id="MyBatis-面试一下"><a href="#MyBatis-面试一下" class="headerlink" title="MyBatis 面试一下"></a>MyBatis 面试一下</h2><h3 id="MyBatis-中-和-区别"><a href="#MyBatis-中-和-区别" class="headerlink" title="MyBatis 中#{}和${}区别"></a>MyBatis 中#{}和${}区别</h3><p><strong>#{}</strong> 是预编译处理，像传进来的数据会加个” “（#将传入的数据都当成一个字符串，会对自动传入的数据加一个双引号）</p>
<p><strong>${}</strong> 就是字符串替换。直接替换掉占位符。$方式一般用于传入数据库对象。</p>
<p>所以为了防止 SQL 注入，能用 <strong>#{}</strong> 的不要去用 <strong>${}</strong></p>
<p>如果非要用 ${} 的话，那要注意防止 SQL 注入问题，可以手动判定传入的变量，进行过滤，一般 SQL 注入会输入很长的一条 SQL 语句</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/56080/">https://curry3035.gitee.io/posts/56080/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%BF%9B%E9%98%B6/">进阶</a><a class="post-meta__tags" href="/tags/MyBatis/">MyBatis</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/5574/" title="每日一面--Thread Pool"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">每日一面--Thread Pool</div></div></a></div><div class="next-post pull-right"><a href="/posts/55120/" title="每日一面--CurrentHashMap"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">每日一面--CurrentHashMap</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/55119/" title="每日一面--Files工具类"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-01</div><div class="title">每日一面--Files工具类</div></div></a></div><div><a href="/posts/34600/" title="面试一下--JUC入门"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-09-10</div><div class="title">面试一下--JUC入门</div></div></a></div><div><a href="/posts/11315/" title="实践一下--Spring Security"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-01</div><div class="title">实践一下--Spring Security</div></div></a></div><div><a href="/posts/40042/" title="每日一面--反射"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-01</div><div class="title">每日一面--反射</div></div></a></div><div><a href="/posts/56511/" title="实践一下--MySQL 优化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-04</div><div class="title">实践一下--MySQL 优化</div></div></a></div><div><a href="/posts/27951/" title="学习--ElasticSearch"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-29</div><div class="title">学习--ElasticSearch</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%B3%E4%BA%8E-MyBatis"><span class="toc-number">1.</span> <span class="toc-text">关于 MyBatis</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF-MyBatis%EF%BC%9F"><span class="toc-number">1.1.</span> <span class="toc-text">什么是 MyBatis？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBatis-%E4%B8%BA%E4%BB%80%E4%B9%88%E8%AF%B4%E4%BB%96%E6%98%AF%E5%8D%8A%E8%87%AA%E5%8A%A8%E5%8C%96%EF%BC%9F"><span class="toc-number">1.2.</span> <span class="toc-text">MyBatis 为什么说他是半自动化？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBatis-%E7%9A%84%E4%BC%98%E7%82%B9%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.3.</span> <span class="toc-text">MyBatis 的优点是什么？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBatis%E6%9C%89%E5%93%AA%E4%BA%9B%E7%BC%BA%E7%82%B9%EF%BC%9F"><span class="toc-number">1.4.</span> <span class="toc-text">MyBatis有哪些缺点？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9%EF%BC%9F"><span class="toc-number">1.5.</span> <span class="toc-text">如何选择？</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatis-%E5%B8%B8%E7%94%A8%E6%A0%87%E7%AD%BE%E5%92%8C%E6%B3%A8%E8%A7%A3"><span class="toc-number">2.</span> <span class="toc-text">MyBatis 常用标签和注解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%86%E8%A7%A3%E4%B8%80%E4%B8%8B"><span class="toc-number">2.1.</span> <span class="toc-text">了解一下</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">2.2.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%A1%B6%E7%BA%A7%E6%A0%87%E7%AD%BE"><span class="toc-number">2.3.</span> <span class="toc-text">顶级标签</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81sql"><span class="toc-number">2.3.1.</span> <span class="toc-text">1、sql</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81insert"><span class="toc-number">2.3.2.</span> <span class="toc-text">2、insert</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81update"><span class="toc-number">2.3.3.</span> <span class="toc-text">3、update</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81delete"><span class="toc-number">2.3.4.</span> <span class="toc-text">4、delete</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8A%A8%E6%80%81sql%E6%A0%87%E7%AD%BE"><span class="toc-number">2.4.</span> <span class="toc-text">动态sql标签</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81if"><span class="toc-number">2.4.1.</span> <span class="toc-text">1、if</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2%E3%80%81choose-when-otherwise"><span class="toc-number">2.4.2.</span> <span class="toc-text">2、choose (when, otherwise)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3%E3%80%81trim-where-set"><span class="toc-number">2.4.3.</span> <span class="toc-text">3、trim (where, set)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4%E3%80%81foreach"><span class="toc-number">2.4.4.</span> <span class="toc-text">4、foreach</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#5%E3%80%81bind"><span class="toc-number">2.4.5.</span> <span class="toc-text">5、bind</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatis-%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">MyBatis 使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81MyBatis-%E4%B8%AD%E7%9A%84-resultType-%E5%92%8C-resultMap"><span class="toc-number">3.1.</span> <span class="toc-text">1、MyBatis 中的 resultType 和 resultMap</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81xml%E4%B8%AD%E7%9A%84timestamp%E6%AF%94%E8%BE%83"><span class="toc-number">3.2.</span> <span class="toc-text">2、xml中的timestamp比较</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81MyBatis-%E6%89%B9%E9%87%8F%E6%8F%92%E5%85%A5"><span class="toc-number">3.3.</span> <span class="toc-text">3、MyBatis 批量插入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%E3%80%81MyBatis-%E4%BC%A0%E9%80%92%E5%A4%9A%E4%B8%AA%E5%8F%82%E6%95%B0"><span class="toc-number">3.4.</span> <span class="toc-text">4、MyBatis 传递多个参数</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E4%B8%80-%E4%BD%BF%E7%94%A8map%E6%8E%A5%E5%8F%A3%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0"><span class="toc-number">3.4.1.</span> <span class="toc-text">方法一:使用map接口传递参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E4%BA%8C-%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E4%BC%A0%E9%80%92%E5%A4%9A%E4%B8%AA%E5%8F%82%E6%95%B0"><span class="toc-number">3.4.2.</span> <span class="toc-text">方法二:使用注解传递多个参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E4%B8%89-%E9%80%9A%E8%BF%87Java-Bean%E4%BC%A0%E9%80%92%E5%A4%9A%E4%B8%AA%E5%8F%82%E6%95%B0"><span class="toc-number">3.4.3.</span> <span class="toc-text">方法三:通过Java Bean传递多个参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E5%9B%9B-%E6%B7%B7%E5%90%88%E4%BD%BF%E7%94%A8"><span class="toc-number">3.4.4.</span> <span class="toc-text">方法四:混合使用</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5%E3%80%81%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AD%97%E6%AE%B5%E5%90%8D%E5%92%8C%E5%AE%9E%E4%BD%93%E7%B1%BB%E5%B1%9E%E6%80%A7%E5%90%8D%E4%B8%8D%E4%B8%80%E8%87%B4%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%88%E9%A9%BC%E5%B3%B0%E5%8C%B9%E9%85%8D%EF%BC%89"><span class="toc-number">3.5.</span> <span class="toc-text">5、数据库字段名和实体类属性名不一致的问题（驼峰匹配）</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9C%BA%E6%99%AF"><span class="toc-number">3.5.1.</span> <span class="toc-text">场景</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E4%B8%80"><span class="toc-number">3.5.2.</span> <span class="toc-text">解决方案一</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E4%BA%8C"><span class="toc-number">3.5.3.</span> <span class="toc-text">解决方案二</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatis%E7%BC%93%E5%AD%98%E6%9C%BA%E5%88%B6"><span class="toc-number">4.</span> <span class="toc-text">MyBatis缓存机制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%86%E8%A7%A3%E4%B8%80%E4%B8%8B-1"><span class="toc-number">4.1.</span> <span class="toc-text">了解一下</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E7%BA%A7%E7%BC%93%E5%AD%98%EF%BC%9A"><span class="toc-number">4.2.</span> <span class="toc-text">一级缓存：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E6%B5%81%E7%A8%8B"><span class="toc-number">4.2.1.</span> <span class="toc-text">具体流程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F"><span class="toc-number">4.2.2.</span> <span class="toc-text">注意</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E7%BA%A7%E7%BC%93%E5%AD%98%EF%BC%9A"><span class="toc-number">4.3.</span> <span class="toc-text">二级缓存：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%89%8D%E8%A8%80-1"><span class="toc-number">4.3.1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B7%E4%BD%93%E6%B5%81%E7%A8%8B-1"><span class="toc-number">4.3.2.</span> <span class="toc-text">具体流程</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">4.4.</span> <span class="toc-text">总结</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#MyBatis-%E9%9D%A2%E8%AF%95%E4%B8%80%E4%B8%8B"><span class="toc-number">5.</span> <span class="toc-text">MyBatis 面试一下</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#MyBatis-%E4%B8%AD-%E5%92%8C-%E5%8C%BA%E5%88%AB"><span class="toc-number">5.1.</span> <span class="toc-text">MyBatis 中#{}和${}区别</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>